import Taro, {Component} from '@tarojs/taro'
import Envs from '../../../../constant/envs'
import {View} from "@tarojs/components"
import {getLocation,getDistance,toast,getFormatDate} from "../../../../utils/index";
import {getClassByClassKey} from "../../../../service/index";

import {getGlobalData,setGlobalData} from "../../../../global.d";

import { AtList, AtListItem,AtButton,AtTabs, AtTabsPane ,AtAccordion } from "taro-ui"
import './index.scss'

export default class Index extends Component {
  config = {
    enablePullDownRefresh:true
  }
  constructor(props) {
    super(props);
    this.state = {
      current: 0,
      user:{},
      id:'',
      signInfo:{},
      timeLeft:0,
      distance:'',
      signed:false,
      open:true,
      open1:false
    }
  }
  componentWillMount(){
    this.setState({
      id:this.$router.params.id
    })
  }
  componentDidMount(){

    this.getList()
    getLocation().then(res=>{
      const { longitude, latitude } = res
      this.setState({
        longitude,
        latitude
      })
    })

    const user = getGlobalData('user')
    this.setState({
      user
    })
    this.time1   =   setInterval(()=>{
     this.getMyDistance().then(res=>{


       this.setState({
         distance:res.toFixed(1)
       })
     })
    },3000)
  }
  componentWillUnmount () {
    clearInterval(this.time1)
    clearInterval(this.time2)
  }
  onPullDownRefresh(){
    this.getList()
  }
  handleClick (value) {
    this.setState({
      current: value
    })
  }
  AtAccordionClick(key,value){
    this.setState({
      [key]: value
    })
  }

  async getMyDistance(){
    let dis = 0
  await  getLocation().then(res=>{
      const { longitude, latitude } = res
       dis =  getDistance(latitude,longitude,this.state.signInfo.latitude,this.state.signInfo.longitude)
      console.log(dis)
    })
   return dis
  }
  getList() {
    Taro.cloud.callFunction({
      name: 'getSign',
      data: {
        id: this.state.id,
        env: Envs.current
      }
    })
      .then(res=>{

        let signInfo = res.result.data
        const date = new Date()
        const time = date.getTime()
        signInfo.startTime = new Date(signInfo.startTime)
        signInfo.endTime = new Date(signInfo.endTime)
        if(signInfo.endTime.getTime()<time){
          signInfo.status = '已结束'
        } else if(signInfo.startTime.getTime()>time){
          signInfo.status = '未开始'
        }else {
          signInfo.status = '进行中'
        this.time2 = setInterval(()=>{
            this.countDown(signInfo.endTime)
          },1000)
        }
        signInfo.stuInfo.forEach((item)=>{
          if(item._id===this.state.user._id){
            this.state.signed = item.signed
          }
        })
        this.setState({
          signInfo
        })

        Taro.setNavigationBarTitle({
          title:signInfo.name
        })
      })
  }

  sign(){
    Taro.showLoading({
      title: '签到中'
    })

    if(this.state.distance>100.0){
      toast('距离签到点距离大于100米，签到失败')
      return
    }else {
      this.getList()
      let stuInfo = this.state.signInfo.stuInfo
      stuInfo = stuInfo.map((item) => {
        if (item._id === this.state.user._id) {
          item.signTime = new Date()
          item.signed = true
        }
        return item
      })
      Taro.cloud.callFunction({
        name:'userSign',
        data:{
          id:this.state.signInfo._id,
          stuInfo,
          env:Envs.current
        }
      }).then(res=>{
        console.log(res)
        Taro.hideLoading()
        toast('签到成功')
        this.setState({
          signed:true
        })
      })
    }
  }

  signButtonText(){
    if(this.state.signed){
      return '已签到'
    } else if(this.state.signInfo.status=== '进行中'){
      return '签到'
    } else if(this.state.signInfo.status=== '未开始'){
      return '签到未开始'
    } else return '你已迟到'
  }
  addZero(i){
    return i < 10 ? "0" + i: i + "";
  }
  countDown(endTime){
    let nowtime = new Date();
    let endtime = new Date(endTime);
    let lefttime = parseInt((endtime.getTime() - nowtime.getTime()) / 1000);
    if(lefttime<100) {
      this.getList()
    }
    let h = parseInt(lefttime / (60 * 60) % 24);
    let m = parseInt(lefttime / 60 % 60);
    let s = parseInt(lefttime % 60);

    h = this.addZero(h);
    m = this.addZero(m);
    s = this.addZero(s);

    this.setState({
      timeLeft:h+'小时'+m+'分'+s+'秒'
    })
  }




  render() {
    const {
      name,
      startTime,
      endTime,
      addressName,
      address,
      latitude,
      longitude,
      status
      } = this.state.signInfo
    const tabList = [{ title: '签到' }, { title: '签到情况' }]
    const {stuInfo} = this.state.signInfo
    const signed = stuInfo?stuInfo.map((item,index)=>{
      if(item.signed){
        let time = new Date(item.signTime)
        const signTime = getFormatDate(time)
        return  <AtListItem
          title={item.name}
          note={'签到时间:'+signTime}
        />
      }
    }):''
    const noSign = stuInfo?stuInfo.map((item,index)=>{
      if(!item.signed){
        return  <AtListItem
          title={item.name}
          extraText={'未签到'}
        />
      }
    }):''
    return (
      <View>
        <AtTabs current={this.state.current} tabList={tabList} onClick={this.handleClick.bind(this)}>
          <AtTabsPane current={this.state.current} index={0} >
            <View className='signInfo'>
              <AtList>
                <AtListItem
                  title='签到地点'
                  extraText={addressName}
                />
                <AtListItem
                  title='地址'
                  note={address}
                />
                <AtListItem
                  title='状态'
                  note={status==='进行中'?'剩余时间：'+this.state.timeLeft:this.state.signInfo.status}
                />
              </AtList>
            </View>
            <View>
              <Map
                className='map'
                latitude={latitude}
                longitude={longitude}
                show-location={true}
                show-scale={true}
                scale={16}
                markers={[{
                  id:0,
                  latitude,
                  longitude,
                  callout:{
                    content:'签到点',
                    display:'ALWAYS',
                    padding:10
                  }
                }]}

              />
            </View>
            <View>
              <AtList>
                <AtListItem
                  title='与签到点相距'
                  extraText={this.state.distance+'米'}
                />
              </AtList>

              <AtButton type='primary'
                        onClick={this.sign.bind(this)}
                        disabled={!(this.state.signInfo.status==='进行中')||this.state.signed}
              >
                {this.signButtonText()}
              </AtButton>
            </View>
          </AtTabsPane>
          <AtTabsPane current={this.state.current} index={1} >
            <AtAccordion
              open={this.state.open}
              onClick={this.AtAccordionClick.bind(this,'open')}
              title='已签到'
            >
              <AtList>
                {signed}
              </AtList>

            </AtAccordion>
            <AtAccordion
              open={this.state.open1}
              onClick={this.AtAccordionClick.bind(this,'open1')}
              title='未签到'
            >
              <AtList>
                {noSign}
              </AtList>

            </AtAccordion>
          </AtTabsPane>

          </AtTabs>



      </View>
    )
  }

}
